import pandas as pd
from pandas import DataFrame
import sys
import os
import time
from parseSKUCode import parseColorSizeCode

# 获取当前路径的函数
def script_path():
    path = os.path.realpath(sys.path[0])
    if os.path.isfile(path):
        path = os.path.basename(path)
    return os.path.abspath(path)

data = pd.DataFrame()

#遍历读取目录下的xlsx文件并按行合并
ori_dir = ''
if len(sys.argv)!=2:
    ori_dir = os.path.join(script_path(), "data")
    print(f"使用默认目标路径：{ori_dir}\n")
else:
    ori_dir = sys.argv[1]
if not os.path.isdir(ori_dir):
    print(f"目标参数不是文件夹. dir={ori_dir}")
    exit()

flist = os.listdir(ori_dir)
for f in flist:
    path = os.path.join(ori_dir, f)
    file_ext = f.rsplit('.',maxsplit=1)
    if os.path.isdir(path):
        continue
    if len(file_ext)!=2:
        continue
    if file_ext[1]!='csv':
        continue

    print(f'process {f}')
    name = file_ext[0]
    ext = file_ext[1]
    nameList = name.rsplit('_',maxsplit=1)
    day = nameList[1]

    if not data.empty:
    	data_t = pd.read_csv(path)
    	data_t.insert(0, 'date', f'{day}')
    	data = data.append(data_t)
    else:
    	data = pd.read_csv(path)
    	data.insert(0, 'date', f'{day}')

data = data.assign(LocalSKU=data['SKU'].apply(parseColorSizeCode))
data = data.assign(SPU=data['LocalSKU'].apply(lambda x:x[1]),Color=data['LocalSKU'].apply(lambda x:x[2]), Size=data['LocalSKU'].apply(lambda x:x[3]),LocalSKU=data['LocalSKU'].apply(lambda x:x[0]))

#今天日期字符串
today = time.strftime("%Y%m%d",time.localtime())

data.to_excel(os.path.join(ori_dir,'流量统计-'+today+'.xlsx'), index=False)
print(data)